package com.jldx.oa.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.jfinal.aop.Before;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jldx.common.NoUtil;
import com.jldx.oa.bean.Article;
import com.jldx.oa.bean.BuyOrder;
import com.jldx.oa.bean.Cart;
import com.jldx.oa.bean.Goods;
import com.jldx.oa.bean.GoodsCategory;
import com.jldx.oa.bean.OrderLine;
import com.jldx.oa.bean.Person;
import com.jldx.oa.bean.SaleOrder;
import com.jldx.oa.bean.User;
import com.jldx.oa.bean.Yuyue;

public class MController extends BaseController {
	public void index() {
		m("login.html");
	}

	public void welcome() {
		m("main.html");
	}

	public void article() {
		List<Article> ls = Article.dao.find("select * from article ");
		setAttr("ls", ls);
		m("article.html");
	}

	public void cart() {
		setAttr("user", JsonKit.toJson(getCurrentUser()));
		m("cart.html");
	}

	public void saleOrder() {
		String sql = "select * from sale_order";
		User lgUser = (User) getSession().getAttribute("lg_user");
		if (lgUser == null) {
			m("login.html");
			return;
		}
		if ("customer".equals(lgUser.getType())) {
			sql += " where partner_id = " + lgUser.getId();
		}
		List<SaleOrder> bos = SaleOrder.dao.find(sql);
		for (SaleOrder so : bos) {
			so.put("state_cn", so.getStateCn());
		}
		setAttr("bos", bos);
		m("sale_order.html");
	}

	public void saleOrderDetail() {
		SaleOrder bo = SaleOrder.dao.findById(getPara("id"));
		setAttr("bo", bo);
		m("sale_order_detail.html");
	}

	// 跳转到下订单挑选商品页面
	public void saleOrderForm() {
		Integer id = getParaToInt("id");
		if (id != null) {
			BuyOrder bo = BuyOrder.dao.findById(id);
			setAttr("bo", bo);
		}
		setAttr("gs", Goods.dao.find("select * from goods"));
		m("sale_order_goods.html");
		// m("sale_order_form.html");
	}

	public void choiceGoods() {
		Integer[] goodsIds = getParaValuesToInt("goods");
		List<Goods> gs = new ArrayList<Goods>();
		for (Integer gid : goodsIds) {
			gs.add(Goods.dao.findById(gid));
		}
		setAttr("gs", gs);
		setAttr("cs", User.dao.getCustomers());
		m("sale_order_form.html");
	}

	public void articleDetail() {
		Article a = Article.dao.findById(getParaToInt("id"));
		setAttr("a", a);
		m("article_detail.html");
	}

	public void me() {
		User user = User.dao.findById(getCurrentUser().getId());
		setAttr("user", user);
		m("myinfo.html");
	}

	public void reg() {
		m("reg.html");
	}

	// cartItems
	public void cartItems() {
		String sql = Db.getSql("oa.userCartList");
		List<Record> items = Db.find(sql, getCurrentUser().getId());
		renderJson(items);
	}

	public void addCard() {
		Integer goodsId = getParaToInt("goodsId");
		Integer cnt = getParaToInt("cnt");
		Goods goods = Goods.dao.findById(goodsId);
		Cart cart = Cart.dao.findFirst("select * from cart where user_id = ? and goods_id = ?",
				getCurrentUser().getId(), goodsId);
		if (cart == null) {
			cart = new Cart();
			cart.setCreateTime(new Date());
			cart.setUserId(getCurrentUser().getId());
			cart.setGoodsId(goodsId);
			cart.setAmount(cnt);
			cart.setMoney(cnt * goods.getPrice());
			cart.save();
		} else {
			cart.setAmount(cart.getAmount() + cnt);
			cart.setMoney(cnt * goods.getPrice());
			cart.update();
		}
		renderText("suc");
	}

	// 更新购物车
	@Before(Tx.class)
	public void updateCartItems() {
		String data = getPara("data");
		System.out.println(data);

		@SuppressWarnings({ "unchecked", "rawtypes" })
		ArrayList<Map> list = new Gson().fromJson(data, ArrayList.class);
		Db.update("delete from cart where user_id = ?", getCurrentUser().getId());
		for (Map m : list) {
			System.out.println(m.get("name"));
			int amount = Integer.parseInt(m.get("amount").toString());
			new Cart().setCreateTime(new Date()).setAmount(amount).setGoodsId(((Double) m.get("goods_id")).intValue())
					.setUserId(getCurrentUser().getId()).save();
		}
		renderText("suc");
	}

	// 下订单
	@Before(Tx.class)
	public void saveOrder() {
		User currentUser = getCurrentUser();
		List<Cart> carts = Cart.dao.find("select * from cart where user_id = ?", currentUser.getId());

		SaleOrder saleOrder = new SaleOrder();
		saleOrder.setPartnerId(currentUser.getId());
		saleOrder.setUserId(currentUser.getId());
		saleOrder.setCreateTime(new Date());
		saleOrder.setNo(NoUtil.createNo("sale"));
		saleOrder.setOtherMoney(0f);
		saleOrder.setState("done");
		saleOrder.save();
		Float money = 0f;
		for (Cart c : carts) {
			OrderLine ol = new OrderLine();
			ol.setOrderId(saleOrder.getId());
			ol.setGoodsId(c.getGoodsId());
			ol.setGoodsCount(c.getAmount());
			ol.setGoodsPrice(c.getGoods().getPrice());
			ol.setMoney(ol.getGoodsCount() * ol.getGoodsPrice());
			ol.save();
			money += ol.getMoney();

			// 更新商品库存
			Goods g = Goods.dao.findById(c.getGoodsId());
			g.setStoreCount(g.getStoreCount() - c.getAmount());
			g.update();
		}

		Integer score = currentUser.getScore();
		saleOrder.setMoney(money);
		User user = getCurrentUser();
		user.setScore(score + money.intValue());
		user.setIsVip(true);
		user.update();
		if (user.getIsVip()) {
			saleOrder.setMoney(money * 0.9f);
		}
		currentUser.update();
		saleOrder.update();
		Db.update("delete from cart where user_id = ?", currentUser.getId());
		renderText("suc");
	}

	// 获取商品列表
	public void goods() {
		setAttr("goods", Goods.dao.find("select * from goods"));
		setAttr("gcs", GoodsCategory.dao.find("select * from goods_category"));
		m("goods.html");
	}

	// 人员列表
	public void person() {
		setAttr("persons", Person.dao.find("select * from person"));
		m("person.html");
	}
	
	//预约
	public void yuyue(){
		//personId:personId,date:d,time:t
		Integer personId = getParaToInt("personId");
		Date d = getParaToDate("date");
		String t = getPara("time");
		
		Yuyue yy = Yuyue.dao.findFirst("select * from yuyue where person_id = ? and yy_date = ? and yy_time= ? ",personId,d,t);
		if(null==yy){
			yy = new Yuyue();
			yy.setUserId(getCurrentUser().getId());
			yy.setPersonId(personId);
			yy.setCreateTime(new Date());
			yy.setYyDate(d);
			yy.setYyTime(t);
			yy.save();
			renderText("suc");
			return;
		}else{
			renderText("has");
		}
	}
	
	//我的预约
	public void myYuyue(){
		List<Yuyue> yys = Yuyue.dao.find("select a.*,b.name person_name,b.type,b.phone from yuyue a left join person b on a.person_id = b.id where a.user_id = ?",getCurrentUser().getId());
		setAttr("yys", yys);
		m("my_yuyue.html");
	}
}
